﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Corina.Interactivity.Silverlight
{
    public class PasswordBoxEnterKeyTrigger : TriggerBase<UIElement>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            PasswordBox pwdBox = this.AssociatedObject as PasswordBox;

            if (pwdBox != null)
            {
                this.AssociatedObject.KeyUp += new System.Windows.Input.KeyEventHandler(AssociatedObject_KeyUp);
            }
            else
            {
                throw new InvalidOperationException("This behavior only works with TextBoxes");
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.KeyUp -= new KeyEventHandler(AssociatedObject_KeyUp);
        }

        private void AssociatedObject_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                PasswordBox pwdBox = AssociatedObject as PasswordBox;

                //This checks for an mvvm style binding and updates the source before invoking the actions.
                BindingExpression expression = pwdBox.GetBindingExpression(PasswordBox.PasswordProperty);
                if (expression != null)
                    expression.UpdateSource();

                InvokeActions(pwdBox.Password);
            }
        }
    }
}
